from fastapi import UploadFile
from pathlib import Path
import aiofiles
import os
import magic
from typing import Optional

from app.core.config import settings


class AudioService:
    """音频处理服务"""

    def __init__(self):
        self.allowed_extensions = settings.ALLOWED_AUDIO_EXTENSIONS
        self.max_file_size = settings.MAX_FILE_SIZE
        self.upload_dir = settings.uploads_path

    def is_audio_file(self, file: UploadFile) -> bool:
        """检查文件是否为音频文件"""
        # 检查扩展名
        if file.filename:
            file_extension = file.filename.split('.')[-1].lower()
            if file_extension not in self.allowed_extensions:
                return False

        # 检查MIME类型
        if file.content_type and not file.content_type.startswith('audio/'):
            return False

        return True

    async def validate_file_size(self, file: UploadFile) -> bool:
        """验证文件大小"""
        return file.size <= self.max_file_size if file.size else True

    async def save_uploaded_file(self, file: UploadFile, meeting_id: int) -> Path:
        """保存上传的音频文件"""
        # 创建会议目录
        meeting_dir = self.upload_dir / f"meeting_{meeting_id}"
        meeting_dir.mkdir(exist_ok=True)

        # 生成文件名
        file_extension = Path(file.filename).suffix if file.filename else '.wav'
        file_path = meeting_dir / f"audio_{meeting_id}{file_extension}"

        # 保存文件
        async with aiofiles.open(file_path, 'wb') as f:
            content = await file.read()
            await f.write(content)

        return file_path

    async def get_audio_duration(self, file_path: Path) -> Optional[float]:
        """获取音频时长"""
        try:
            # TODO: 使用librosa或pydub获取音频时长
            # 这里需要安装相应的库
            import librosa
            duration = librosa.get_duration(path=str(file_path))
            return duration
        except Exception:
            return None

    async def validate_audio_file(self, file_path: Path) -> bool:
        """验证音频文件是否有效"""
        try:
            # 使用python-magic检测文件类型
            file_type = magic.from_file(str(file_path), mime=True)
            return file_type.startswith('audio/')
        except Exception:
            return False

    async def convert_audio_format(self, input_path: Path, output_format: str = 'wav') -> Path:
        """转换音频格式"""
        try:
            # TODO: 使用pydub或ffmpeg转换音频格式
            output_path = input_path.with_suffix(f'.{output_format}')
            # 转换逻辑
            return output_path
        except Exception:
            return input_path

    async def get_audio_info(self, file_path: Path) -> dict:
        """获取音频文件信息"""
        try:
            # TODO: 使用mutagen或类似库获取音频信息
            return {
                "duration": await self.get_audio_duration(file_path),
                "size": file_path.stat().st_size,
                "format": file_path.suffix,
                "valid": await self.validate_audio_file(file_path)
            }
        except Exception:
            return {
                "duration": None,
                "size": 0,
                "format": file_path.suffix,
                "valid": False
            }